from django import template
from django import forms
from django.http import HttpResponse, HttpResponseRedirect
from django.utils import simplejson
from pirate_messages.models import Notification
from django.db import transaction
from django.middleware import csrf
from django.contrib.contenttypes.models import ContentType
from pirate_profile.models import Profile
from django.utils.encoding import smart_str
from pirate_core.helpers import clean_html
from pirate_core.views import template_for_model

import datetime
from pirate_signals.models import notification_send

from django.shortcuts import get_object_or_404

from pirate_core.views import HttpRedirectException, namespace_get

from customtags.decorators import block_decorator
register = template.Library()
block = block_decorator(register)

get_namespace = namespace_get('pp_messages')


@block
def pp_has_mail(context, nodelist, *args, **kwargs): 
    context.push()
    namespace = get_namespace(context)

    user = kwargs.get('user', None)
    
    notes = Notification.objects.all()
    notes = notes.filter(receiver=user,is_read=False)
    count = len(list(notes))
    
    if count == 0: has_mail = False
    else: has_mail = True
    namespace['has_mail'] = has_mail
    namespace['count'] = count
    
    output = nodelist.render(context)
    context.pop()

    return output


@block
def pp_notification_unread_list_get(context, nodelist, *args, **kwargs): 
    context.push()
    namespace = get_namespace(context)

    user = kwargs.get('user', None)
    
    notes = Notification.objects.all()
    notes = notes.filter(receiver=user,is_read=False)
    notes = notes.order_by('-submit_date')
    for i in notes:
        i.is_read = True
        i.save()
    
    namespace['notifications'] = notes
    
    output = nodelist.render(context)
    context.pop()

    return output


@block
def pp_notification_read_list_get(context, nodelist, *args, **kwargs): 
    context.push()
    namespace = get_namespace(context)

    user = kwargs.get('user', None)
    
    notes = Notification.objects.all()
    notes = notes.filter(receiver=user,is_read=True)
    notes = notes.order_by('-submit_date')
    for i in notes:
        i.is_read = True
        i.save()
    
    namespace['notifications'] = notes
    
    output = nodelist.render(context)
    context.pop()

    return output
